package com.joyoung.common.ui;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;


import com.joyoung.common.BaseApplication;
import com.joyoung.common.service.ServiceManagerFactory;

import java.util.List;

/**
 * 初始化的FragmentLifecycleCallbacks
 *
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public class InitFragmentLifecycleCallback extends FragmentManager.FragmentLifecycleCallbacks {
    
    @Override
    public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) {
        super.onFragmentAttached(fm, f, context);
        injectAddUILayer(f);
    }
    
    @Override
    public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
        super.onFragmentCreated(fm, f, savedInstanceState);
        injectAddLifecycleObservers(f);
    }
    
    @Override
    public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) {
        super.onFragmentViewDestroyed(fm, f);
        injectRemoveLifecycleObservers(f);
    }
    
    @Override
    public void onFragmentDetached(FragmentManager fm, Fragment f) {
        super.onFragmentDetached(fm, f);
        injectRemoveUILayer(f);
    }
    
    protected void injectAddUILayer(Fragment f) {
        //没有需求不处理
//        if (f instanceof DialogFragment) {
//
//        }
    }
    
    protected void injectRemoveUILayer(Fragment f) {
    }
    
    protected void injectAddLifecycleObservers(Fragment f) {
        // 为服务添加生命周期观察
        BaseApplication.setLastLifecycleOwner(f);
        Lifecycle lifecycle = BaseApplication.getLastLifecycleOwner().getLifecycle();
        List<LifecycleObserver> lifecycleObservers = ServiceManagerFactory.getInstance().getAll(LifecycleObserver.class);
        for (LifecycleObserver observer : lifecycleObservers) {
            lifecycle.addObserver(observer);
        }
    }
    
    protected void injectRemoveLifecycleObservers(Fragment f) {
        // 去除服务的生命周期观察
        BaseApplication.setLastLifecycleOwner(null);
        Lifecycle lifecycle = (f).getLifecycle();
        List<LifecycleObserver> lifecycleObservers = ServiceManagerFactory.getInstance().getAll(LifecycleObserver.class);
        for (LifecycleObserver observer : lifecycleObservers) {
            lifecycle.removeObserver(observer);
        }
    }
    
}
